package top.infopub.util;


import java.text.DateFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * JsonUtils
 * @author Awoke
 * @version 2018年9月14日
 * @see JsonUtils
 * @since
 */
public class JsonUtils extends JsonFormatter {

    private static final Logger LOG = LoggerFactory.getLogger(JsonUtils.class);

    public static String toString(Object obj) {
        if (obj instanceof String) {
            return (String)obj;
        }
        else if (null == obj) {
            return null;
        }
        try {
            return JsonFormatter.toJsonString(obj);
        }
        catch (Exception e) {
            LOG.error("JsonFormatter.toJsonString error: ", e);
        }
        return null;
    }

    public static String toString(Object obj, DateFormat dateFormat) {
        if (obj instanceof String) {
            return (String)obj;
        }
        else if (null == obj) {
            return null;
        }
        try {
            JsonFormatter.setDateFormat(dateFormat);
            return JsonFormatter.toJsonString(obj);
        }
        catch (Exception e) {
            LOG.error("", e);
        }
        return null;
    }

    public static <T> T toBean(Object obj, Class<T> cls) {
        if (null == obj) {
            return null;
        }
        try {
            return JsonFormatter.toObject(JsonUtils.toString(obj), cls);
        }
        catch (Exception e) {
            LOG.error("JsonFormatter.toObject error: ", e);
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public static List<Map<String, Object>> toList(Object obj) {
        List<Map<String, Object>> lists = new LinkedList<Map<String, Object>>();
        List<Object> list = JsonUtils.toBean(obj, List.class);
        if (null != list) {
            for (Object object : list) {
                Map<String, Object> map = JsonUtils.toBean(object, HashMap.class);
                if (null != map) {
                    lists.add(map);
                }
            }
        }
        return lists;
    }

    @SuppressWarnings("unchecked")
    public static <T> List<T> toList(Object obj, Class<T> cls) {
        List<T> lists = new LinkedList<T>();
        List<Object> list = JsonUtils.toBean(obj, List.class);
        if (null != list) {
            for (Object object : list) {
                T t = JsonUtils.toBean(object, cls);
                if (null != t) {
                    lists.add(t);
                }
            }
        }
        return lists;
    }
}
